// pages/discount/SearchCoupon.js
let network = null;
let api = null;
const app = getApp();
var Zan = require('../../dist/index');
let start = 0;

Page(Object.assign({}, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    couponList: [],
    recordsTotal: 0,
    value: '',
    nodata: {
      msg: '暂无数据',
      notype: 1,
      imgurl: '/images/nodatas.png',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    api = new app.Api();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.couponList.length < this.data.recordsTotal) {
      start = start + 20;
      network._post_page_json(this, api.searchCoupon, start, { search: this.data.value }, success);
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }

  // bindSearchInput: function (e) {
  //   this.setData({
  //     inputValue: e.detail.value
  //   })
  // },

  search: function (e) {
    start = 0;
    wx.stopPullDownRefresh();
    this.setData({
      couponList: [],
      value: e.detail.value
    });
    if (this.data.value) {
      network._post_page_json(this, api.searchCoupon, start, { search: e.detail.value }, success);
    } else {
      this.showZanTopTips(this.prompt, '请输入关键字');
    }
  },

  /**
   * 进入优惠券详情
   */
  goCouponDetails: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/discount/CouponDetails' + '?couponId=' + id,
    })
  }
}))

var success = function (that, res) {
  if (res.data.data) {
    that.setData({
      couponList: that.data.couponList.concat(res.data.data),
      recordsTotal: res.data.recordsTotal
    })
  }
}